package cn.steel.controller.buyer;

import cn.steel.domain.entity.Message;
import cn.steel.domain.entity.Order;
import cn.steel.domain.entity.User;
import cn.steel.service.MessageService;
import cn.steel.service.OrderService;
import cn.steel.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/buyer/message")
@RequiredArgsConstructor
public class BuyerMessageController {

    private final UserService userService;
    private final MessageService messageService;
    private final OrderService orderService;

    // 购买商消息页面：显示有交易关系的供应商列表
    @GetMapping
    public String messagePage(Model model) {
        // 获取当前登录用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User buyer = userService.getUserByUsername(currentUsername);

        if (!"BUYER".equals(buyer.getRole())) {
            throw new IllegalStateException("只有购买商可以访问此页面");
        }

        // 获取有交易关系的供应商列表
        List<User> allSuppliers = userService.findUsersByRole("SUPPLIER");
        Set<Long> supplierIdsWithOrders = userService.findSuppliersWithOrders(buyer.getId());
        List<User> suppliers = allSuppliers.stream()
                .filter(supplier -> supplierIdsWithOrders.contains(supplier.getId()))
                .collect(Collectors.toList());

        for (User supplier : suppliers) {
            long unreadCount = messageService.getUnreadMessageCount(buyer.getId());
            supplier.setUnreadCount(unreadCount); // 临时字段，用于前端显示
        }
        model.addAttribute("suppliers", suppliers);
        log.info("Loaded buyer message page, suppliers count={}", suppliers.size());
        return "buyer/message";
    }

    // 查看与某个供应商的聊天记录
    @GetMapping("/chat/{supplierId}")
    public String chatWithSupplier(@PathVariable Long supplierId, Model model) {
        // 获取当前登录用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User buyer = userService.getUserByUsername(currentUsername);

        if (!"BUYER".equals(buyer.getRole())) {
            throw new IllegalStateException("只有购买商可以访问此页面");
        }

        // 获取供应商信息
        User supplier = userService.getUserById(supplierId);
        if (!"SUPPLIER".equals(supplier.getRole())) {
            throw new IllegalStateException("只能与供应商聊天");
        }

        // 验证是否有交易关系
        Set<Long> supplierIdsWithOrders = userService.findSuppliersWithOrders(buyer.getId());
        if (!supplierIdsWithOrders.contains(supplierId)) {
            throw new IllegalStateException("您与该供应商没有交易记录");
        }

        // 获取聊天记录并标记为已读
        List<Message> messages = messageService.getMessagesBetweenUsers(supplierId, buyer.getId());
        messageService.markMessagesAsRead(supplierId, buyer.getId());

        // 获取有交易关系的供应商列表用于左侧显示
        List<User> allSuppliers = userService.findUsersByRole("SUPPLIER");
        List<User> suppliers = allSuppliers.stream()
                .filter(s -> supplierIdsWithOrders.contains(s.getId()))
                .collect(Collectors.toList());

        for (User s : suppliers) {
            long unreadCount = messageService.getUnreadMessageCount(buyer.getId());
            s.setUnreadCount(unreadCount);
        }
        // 获取当前用户的订单
        List<Order> orders = orderService.findOrdersByBuyerId(buyer.getId());
        model.addAttribute("orders", orders);

        model.addAttribute("contacts", suppliers);
        model.addAttribute("contact", supplier);
        model.addAttribute("selectedContactId", supplierId);
        model.addAttribute("messages", messages);
        model.addAttribute("currentUserId", buyer.getId());
        model.addAttribute("role", "BUYER");
        log.info("Loaded chat page for buyerId={} and supplierId={}", buyer.getId(), supplierId);
        return "buyer/chat";
    }

    @PostMapping("/send")
    public String sendMessage(@RequestParam Long receiverId, @RequestParam Long senderId, @RequestParam String content, Model model) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User buyer = userService.getUserByUsername(currentUsername);

        if (!"BUYER".equals(buyer.getRole())) {
            throw new IllegalStateException("只有购买商可以发送消息");
        }

        User receiver = userService.getUserById(receiverId);
        if (!"SUPPLIER".equals(receiver.getRole())) {
            throw new IllegalStateException("只能向供应商发送消息");
        }

        messageService.sendMessage(senderId, receiverId, content);

        return "redirect:/buyer/message/chat/" + receiverId;
    }
    @GetMapping("/orders")
    @ResponseBody
    public List<Order> getOrders() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String currentUsername = userDetails.getUsername();
        User buyer = userService.getUserByUsername(currentUsername);

        if (!"BUYER".equals(buyer.getRole())) {
            throw new IllegalStateException("只有购买商可以查看订单");
        }

        List<Order> orders = orderService.findOrdersByBuyerId(buyer.getId());
        log.info("Fetched orders for buyerId={}, order count={}", buyer.getId(), orders.size());
        return orders;
    }
}